import json
import random
import re
from time import sleep
from urllib import parse

import requests
from requests import RequestException

import user_agents


def get_one_page(url):
    """
    根据url获取页面内容
    :param url: 访问页面的URL地址
    :return: 返回html内容
    """
    try:
        headers = {'User-Agent': random.choice(user_agents.agents)}
        response = requests.get(url, headers=headers)
        response.encoding = response.apparent_encoding
        if response.status_code == 200:
            # print(response.text)
            return response.text
        return None
    except RequestException:
        return None


def parse_page(html):
    """
    用正则表达式解析页面内容
    :param html: 页面html
    :return: 电影结果字典
    """
    pattern = re.compile('<li.*?gl-item.*?>.*?'
                         'p-img.*?<a.*?href="(.*?)".*?[data\-lazy\-img|src]="//(.*?)".*?</a>.*?'
                         'p-price.*?<i>(.*?)</i>.*?'
                         'p-name.*?<i.*?>(.*?)</i>.*?'
                         'p-commit.*?<strong>.*?<a.*?>(.*?)</a>(.*?)</strong>.*?'
                         'p-shop.*?<a.*?>(.*?)</a>.*?'
                         '</li>', re.S)
    items = re.findall(pattern, html)

    for item in items:
        yield {
            'href': item[0],  # 链接
            'image': item[1],  # 图片
            'price': item[2],  # 价格
            'name': item[3],  # 名字
            'commit': item[4] + item[5],  # 评价
            'shop': item[6]  # 店铺名称
        }


def save_file(content):
    """
    保存电影信息
    :param content: 电影信息
    """
    with open('product.txt', 'a', encoding='utf-8') as f:
        f.write(json.dumps(content, ensure_ascii=False) + '\n')


def main(offset, name):
    data = {
        'keyword': name,
        'enc': 'utf-8',
        'wq': name,
        'page': offset
    }
    url = 'https://search.jd.com/Search?' + parse.urlencode(data)
    print(url)
    html = get_one_page(url)
    parse_page(html)
    if html:
        for val in parse_page(html):
            save_file(val)


if __name__ == '__main__':
    product_name = input('请输入您所需爬取的商品名称:')
    for i in range(10):
        main(offset=2 * i + 1, name=product_name)
        sleep(2)
    print('完成')
